package com.summer.report.common.service;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.summer.report.common.domain.ReportDataSource;
import com.summer.report.common.domain.ReportDataSourceExample;
import com.summer.report.common.mapper.ReportDataSourceMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ReportDataSourceServiceImpl extends ServiceImpl<ReportDataSourceMapper, ReportDataSource> implements ReportDataSourceService{

    @Autowired
    private ReportDataSourceMapper reportDataSourceMapper;


    /**
     * 测试数据库连接是否能成功
     * @param reportDataSource
     * @return
     */
    @Override
    public Map<String, Object> testConnect(ReportDataSource reportDataSource) {
        Map<String,Object> result=new HashMap<>();

        DruidDataSource dataSource = createDataSource(reportDataSource);
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        try {
            factoryBean.setMapperLocations(resolver.getResources("classpath:mapper/ExeSql.xml"));
            factoryBean.setTypeAliasesPackage("ExeSql");
            SqlSessionFactory sqlSessionFactory = factoryBean.getObject();
            SqlSession sqlSession = sqlSessionFactory.openSession();

            Connection connection = sqlSession.getConnection();
            if (connection!=null){
                result.put("result", true);
                connection.close();
            }

            sqlSession.close();
        } catch (Exception e) {
            result.put("result", false);
            result.put("msg" , e.getMessage());
        }
        return result;
    }

    public DruidDataSource createDataSource(ReportDataSource reportDataSource){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(reportDataSource.getDriverClass());
        dataSource.setUrl(reportDataSource.getUrl());
        dataSource.setUsername(reportDataSource.getUsername());
        dataSource.setPassword(reportDataSource.getPassword());
        dataSource.setDbType(reportDataSource.getType());
        //连接最大等待时间
        dataSource.setMaxWait(20000);
        dataSource.setConnectionErrorRetryAttempts(0);
        dataSource.setBreakAfterAcquireFailure(true);
        return dataSource;
    }
}
